package com.heima.basic.DeadLock;

/**
 * @Author: Ethan Yankang
 * @Program: 面试必会代码
 * @Date: 2024-09-06 08:09
 **/
public class DeadLock {
    public static void main(String[] args) {
        Obj1 obj1 = new Obj1();
        Obj2 obj2 = new Obj2();
        Thread threadOfdeadLockExample1 = new Thread(new DeadLockExample(obj1, obj2, 1, 2, true),"线程1");
        Thread threadOfdeadLockExample2 = new Thread(new DeadLockExample(obj1, obj2, 1, 2, false),"线程2");
        threadOfdeadLockExample1.start();
        threadOfdeadLockExample2.start();
    }

    public static class DeadLockExample implements Runnable{
        Obj1 obj1;
        Obj2 obj2;
        int a=1;
        int b=2;
        boolean flag=true;
        public DeadLockExample(Obj1 obj1, Obj2 obj2, int a, int b, boolean flag) {
            this.obj1 = obj1;
            this.obj2 = obj2;
            this.a = a;
            this.b = b;
            this.flag = flag;
        }
        @Override
        public void run() {
            if (flag){
                synchronized (obj1){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (obj2){
                        System.out.println(a + b);
                    }
                }
            }else {
                synchronized (obj2){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (obj1){
                        System.out.println(a + b);
                    }
                }
            }
        }
    }
    public static class Obj1{
    }
    public static  class  Obj2{
    }
}

